<?php
/**
 * @author Nakul Ganesh S
 * GSoC 2008
 * @mentor Deborah Susan Clarkson
 * 
 * @author Daniel Ghilea
 * GSoC 2009
 * @mentor Andrey Mishenin
 * 
 * @package		Joomla
 * @subpackage	Content
 * @copyright	Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved.
 * @license		GNU/GPL, see LICENSE.php
 * Joomla! is free software. This version may have been modified pursuant to the
 * GNU General Public License, and as distributed it includes or is derivative
 * of works licensed under the GNU General Public License or other free or open
 * source software licenses. See COPYRIGHT.php for copyright notices and
 * details.
 */
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
/**
 * Weblinks Weblink Controller
 *
 * @package		Joomla
 * @subpackage	Weblinks
 * @since 1.5
 */
class MediaControllerStudio extends MediaController
{
	/**
	 * Display the Joomla! Studio 
	 *
	 * @param none
	 * 
	 */
	
	function display()
	{
		jimport('joomla.filesystem.path');
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');
        
        // Disable cache		
		Header("Cache-control: private, no-cache");
		Header("Expires: Mon, 26 Jun 1997 05:00:00 GMT");
		Header("Pragma: no-cache");
        Header ("Last-Modified: " . gmdate ("D, d M Y H:i:s") . " GMT");
		
        
		parent::display();	
		
	}
	
	/**
	 * Edits images and save them.
	 * Includes
	 * 
	 * 
	 */

	function image()
    {
	        global $mainframe;
	        jimport('joomla.filesystem.path');
	        // Set FTP credentials, if given
	        jimport('joomla.client.helper');
	        JClientHelper::setCredentialsFromRequest('ftp');
			jimport('JImageLib.JImageLib');
			
			
			//Absolute image path 
			$paths = JRequest::getVar('im', 'array()', '', 'array');
			//The image parent folder
	        $folder = JRequest::getVar('folder', '', '', 'path');
	        //The destination folder
			$savepaths = JRequest::getVar('img', '', '', 'name');
			
			//Width for image resizing
			$width = (int)JRequest::getInt('width',0,'POST');
			//Height for image resizing
			$height = (int)JRequest::getInt('height', 0,'POST');
			
			//Resize option 
			$resize = JRequest::getVar('resize','','POST');
			$resizecolor = JRequest::getVar('resizecolor','','POST');
			
			
			//Degree of image rotation 
			$rotate = (int)JRequest::getInt('rotate','','POST');
			
			//Flip orientation (H or V)
			$flip = JRequest::getVar('flip','','POST');
			
						
			//Grayscale T or F
			$greyscale = JRequest::getVar('greyscale','','POST');
			//Edge Detect T or F
			$edgedetect = JRequest::getVar('edgedetect','','POST');
			//Mean Removal T or F
			$meanrm = JRequest::getVar('meanrm','','POST');
			//Sepia T or F
			$sepia = JRequest::getVar('sepia','','POST');
			//Gaussian Blur T or F
			$blur = JRequest::getVar('blur','','POST');
			//Emboss T or F
			$emboss = JRequest::getVar('emboss','','POST');
			//Drop Shadow T or F
			$drop = JRequest::getVar('drop','','POST');
			//Negate T or F
			$negate = JRequest::getVar('negate','','POST');
			
			//Image Colorize (rgb)
			$r = (int)JRequest::getInt('r', 0,'POST');
			$g = (int)JRequest::getInt('g', 0,'POST');
			$b = (int)JRequest::getInt('b', 0,'POST');
			
			//Brightness set
			$bright = (int)JRequest::getInt('bright','','POST');
			//Contrast set
			$contrast = (int)JRequest::getInt('contrast','','POST');
			
			
			//Smoothness T or F
			$opacity = (int)JRequest::getVar('opacity','','POST');
			
			//Image crop w=width,h=height,x&y coordinates
			$w = (int)JRequest::getInt('w', 0,'POST');
			$h = (int)JRequest::getInt('h', 0,'POST');
			$x = (int)JRequest::getInt('x', 0,'POST');
			$y = (int)JRequest::getInt('y', 0,'POST');
	
			
			// Image Library
			$image_lib = JRequest::getVar('imagelib','','POST');
			
			
	        	if (count($paths))
	        		{	
	            		foreach ($paths as $path)
	            			{
								$image_path =$path;
	              			}	
				  	}
	        
	
			$site_path = str_replace('\\', '/', realpath(JPATH_SITE)) . '/';
			$image_path = str_replace('\\', '/', $image_path);
			$image_path = str_replace($site_path, '', $image_path); 
			
			$image = new JImageLib();

			if (! $image->load($image_path)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
			}
		  
			if ($image_lib){
				if (! $image->setImageLib($image_lib)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			
			
			//Get image extension
		 	$ext = strtolower(end(explode('.', $image_path)));
		 	//Path where the temporary image is to be stored for UNDO
		 	$unopath = JPATH::clean(JPATH_SITE . DS ."images".DS."tmp". DS . "uno." . $ext);
			
		 	/*
		 	* Create the image according to its type,
		 	* Quality of JPEG set to 90,
		 	* unopath saves a copy of the original file for "undo" purpose
		 	*/
			if (! $image->save($unopath, 90)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
			}

			//Create a copy of the newly created image 
			$tmppath = JPATH::clean(JPATH_SITE . DS ."images".DS."tmp".DS. 'tmpimg.'.$ext);
			
			
			
			
			//Resizing the Image
			if($width || $height) 
			{ 
				if ($width){
					if (! $image->setWidth($width)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
					}
				}
				if ($height){
					if (! $image->setHeight($height)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
					}
				}
				if ($resize){
					if ($resize == 'default') $resize = JImageLib::DEFAULT_RESIZE_OPTION;
					if ($resize == 'fill'){
						if ($resizecolor){
							if (! $image->setResizing($resize, $resizecolor)){
								$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
							}
						}
					}
					else if (! $image->setResizing($resize)){
							$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
						}
				}
			}
			

			/*Flip H or V */
			if ($flip)
			{
				if (! $image->setFlipping($flip)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
	
	
			/* Filters */

			/*Drop Shadow */
			if($drop) 
			{
				if (! $image->setFilter('dropshadow')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			
			if($greyscale) 
			{
				if (! $image->setFilter('grayscale')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($edgedetect) 
			{
				if (! $image->setFilter('edgedetect')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($meanrm) 
			{
				if (! $image->setFilter('meanremoval')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
	
			if($sepia) 
			{
				if (! $image->setFilter('sepia')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($emboss)
			{
				if (! $image->setFilter('emboss')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($negate)
			{
				if (! $image->setFilter('negative')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($blur)
			{
				if (! $image->setFilter('blur')){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			
		
			if($bright)
			{
				if (! $image->setFilter('brightness', $bright)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($contrast)
			{
				if (! $image->setFilter('contrast', $contrast)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			if($opacity)
			{
				$opacity = -$opacity;
				if (! $image->setFilter('smoothness', $opacity)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
			/*Colorize*/
			if($r || $g || $b)
			{
				// Transform the rgb values to a hex color code for the colorize param				
				$color = "#".(strlen(dechex($r)) < 2?'0':'').dechex($r).(strlen(dechex($g)) < 2?'0':'').dechex($g).(strlen(dechex($b)) < 2?'0':'').dechex($b);
				if (! $image->setFilter('colorize', $color)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}				
			}
	
			
			/*CROP*/
			if($x || $y || $w || $h)
			{
				if (! $image->setWidth($w)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
				if (! $image->setHeight($h)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
				if (! $image->setCropping($x, $y)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}
		
	
			/* Rotation  */
			if($rotate) 
			{
				if (! $image->setRotation($rotate)){
					$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
				}
			}

			// Saving the image to tmppath
			
			if (! $image->save($tmppath)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
			}

	        $mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder=tmp&im[]=tmpimg.'.$ext );
	}

	
function undo()
    {
        global $mainframe;
        jimport('joomla.filesystem.path');
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');
		
		$paths = JRequest::getVar('im', 'array()', '', 'array');
        $folder = JRequest::getVar('folder', '', '', 'path');
          if (count($paths))
        {
            foreach ($paths as $path)
            {
				$image_path =$path;
                
            }
        }
        echo $folder;
        $ext = strtolower(end(explode('.', $image_path)));
         $unopath =JPATH::clean(JPATH_SITE . DS ."images".DS."tmp". DS . "uno." . $ext);
         $tmppath = JPATH::clean(JPATH_SITE . DS ."images".DS."tmp". DS . "tmpimg." . $ext);
        
         $i = substr_count($image_path,"tmpimg");
      if($i)
      {		copy($unopath,$image_path);
      $mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext );	
	}

        

}
function save()
    {
        global $mainframe;
        jimport('joomla.filesystem.path');
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');
		
		jimport('JImageLib.JImageLib');
		
		$image = new JImageLib();
		
		$paths = JRequest::getVar('im', 'array()', '', 'array');
        $folder = JRequest::getVar('folder', '', '', 'path');
        $savefolder = JRequest::getVar('savefolder', '', '', 'path');
        $savename = JRequest::getVar('savename', '', '', 'path');
        $quality = (int)JRequest::getInt('quality', 90,'POST');
		// Image Library
		$image_lib = JRequest::getVar('imagelib','','POST');
        
    	if ($image_lib){
			if (! $image->setImageLib($image_lib)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );
			}
		}
			
        if (count($paths))
        {
            foreach ($paths as $path)
            {
				$image_path =$path;
                
            }
        }
		
         $ext = strtolower(end(explode('.', $image_path)));
         $savepath = JPATH::clean(JPATH_SITE . DS . "images". DS . $savefolder. DS . $savename);
         $tmppath = JPATH::clean("images".DS."tmp". DS . "tmpimg." . $ext);

		if (! $image->load($tmppath)){
			$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );	
		}
		 
		if (! $image->save($savepath, $quality)){
			$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext, $image->getError(), 'error' );	
		}
		else		
		{		
     	 $mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]=tmpimg.'.$ext );	
		}

        

}
function generate()
    {
        global $mainframe;
        
        jimport('joomla.filesystem.path');
        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        JClientHelper::setCredentialsFromRequest('ftp');
		
        jimport('JImageLib.JImageLib');
        
        
		$paths = JRequest::getVar('im', 'array()', '', 'array');
        $folder = JRequest::getVar('folder', '', '');
        
        //Width for thumbnailing
		$width = (int)JRequest::getInt('width',0,'POST');
		//Height for thumbnailing
		$height = (int)JRequest::getInt('height', 0,'POST');
			
        
        // Custom name for the generated images
        $savefolder = JRequest::getVar('savefolder', '', 'POST');
        $savename = JRequest::getVar('savename', '', 'POST');
        
        // or
        
        // Prefix
        $prefix = JRequest::getVar('prefix', '', 'POST');

        // Directory
        $directory = JRequest::getVar('directory', '', 'POST');
        
        // Use image size
        $use_size = JRequest::getVar('usesize', '', 'POST');
        
        
        // Image Library
        if (isset($_POST['thumbnail'])){
			$image_lib = JRequest::getVar('tn_imagelib','','POST');
        }
        else {
        	$image_lib = JRequest::getVar('wm_imagelib','','POST');
        }
			
			
    	if (count($paths))
        {
            foreach ($paths as $path)
            {
				$image_path =$path;
                
            }
        }
        
        
    	$site_path = str_replace('\\', '/', realpath(JPATH_SITE)) . '/';
		$image_path = str_replace('\\', '/', $image_path);
		$image_path = str_replace($site_path, '', $image_path); 
		
		$ext = strtolower(end(explode('.', $image_path)));
		
		$image = new JImageLib();
		
		if (! $image->load($image_path)){
			$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path , $image->getError(), 'error' );
		}
	  
		if ($image_lib){
			if (! $image->setImageLib($image_lib)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
			}
		}
			
        if ($savename){
        	if ($savefolder){
        		$savefolder = $savefolder . DS;
        	}
        	
        	if (! $image->setName('images' . DS . $savefolder . $savename)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
			}
        }
		
        if ($prefix){
        	if (! $image->setPrefix($prefix)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
			}
        }
        
    	if ($directory){
        	if (! $image->setDirectory('images' . DS . $directory)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
			}
        }
        
    	if ($use_size){
        	if (! $image->setUseImageSize($use_size)){
				$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
			}
        }
        
        
        if (isset($_POST['thumbnail'])){
       			if ($width){
					if (! $image->setWidth($width)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
					}
				}
				if ($height){
					if (! $image->setHeight($height)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
					}
				}
				
        		if (! $generated_image = $image->getThumbnail()){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$image_path, $image->getError(), 'error' );
				}
        }
        else {
        	 // Watermark folder and filename
        	$wmfolder = JRequest::getVar('wmfolder', '', 'POST');
        	$wmname = JRequest::getVar('wmname', '', 'POST');
        	
        	
        	// Watermark text, font-family, font-size and font-color
        	$text = JRequest::getVar('text', '', 'POST');
        	$font = JRequest::getVar('font', '', 'POST');
        	$fontsize = (int)JRequest::getInt('fontsize', '', 'POST');
        	$fontcolor = JRequest::getVar('fontcolor', '', 'POST');
			
        	if (! $font) $font = JImageLib::DEFAULT_WM_FONT_FAMILY;
			if (! $fontsize) $fontsize = JImageLib::DEFAULT_WM_FONT_SIZE;
			if (! $fontcolor) $fontcolor = JImageLib::DEFAULT_WM_FONT_COLOR;
        	$fontsize = (int)$fontsize;
			
			// Watermark position
        	$position = JRequest::getVar('position', '', 'POST');
        	if (! $position) $position = JImageLib::DEFAULT_WM_POSITION;
        			
			
		
		
        	if ($wmname){
	        	if ($wmfolder){
	        		$wmfolder = $wmfolder . DS;
	        	}
	        	
	        	$wmpath = 'images' . DS . $wmfolder . $wmname;
	        	$wmpath = str_replace('\\', '/', $wmpath);
	        	
        		if (! $generated_image = $image->addWatermark($wmpath , $position)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$path, $image->getError(), 'error' );
				}
        	}
        	else if ($text){
        		if (! $generated_image = $image->addWatermarkText($text, $font, $fontsize, $fontcolor, $position)){
						$mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$path, $image->getError(), 'error' );
				}
        	}
        }
        
        
        $mainframe->redirect('index.php?option=com_media&task=studio.display&view=studio&tmpl=component&folder='.$folder.'&im[]='.$path, 'The image \''. $generated_image .'\' was generated succesfully!');
       
}


}

